<?php

namespace app\admin\controller;

use app\admin\model\User as ModelUser;
use app\BaseController;
use frame\lib\Db;
use frame\lib\VerfiyParam;

class User extends Base
{
    public function index()
    {
        $this->view('index');
    }
    public function list()
    {
        $username = @$_GET['username'];
        $start = @$_GET['start'];
        $end = @$_GET['end'];
        $query = ['username' => $username, 'start' => $start, 'end' => $end];
        success(ModelUser::list($username));
    }
    public function edit()
    {
        $data = Db::name('user')->where(['id' => $_GET['id']])->find();
        $this->view('edit', ['data' => $data]);
    }
    public function doEdit()
    {
        $param = $_POST;
        $uid = @$param['id'];
        $data = [];
        $rule = [
            'vip_time|会员时长' => 'int',
            'score|积分' => 'int',
            'email|邮箱' => 'email',
            'status|邮箱' => 'in:1,0,2',
            'type_s|会员操作类型' => 'in:1,2',
            'id' => 'require|int',
            'password|密码' => 'min:6|max:12|alphaNum'
        ];
        VerfiyParam::init($param, $rule);
        $user = Db::name('user')->where(['id' => $uid])->find();
        $user_vip_time = getTime(3, $user['vip_time']) < time() ? time() :  getTime(3, $user['vip_time']);
        if (@$param['type_s'] == 1) {
            $vip_time = $user_vip_time + @$param['vip_time'];
        } else {
            $vip_time = $user_vip_time - @$param['vip_time'];
            $vip_time = $vip_time < 0 ? 0 : $vip_time;
        }
        if (!$user) error('用户不存在');
        $data['password'] = @$param['password'] ? encrypt_pwd($param['password']) : $user['password'];
        $data['email'] = @$param['email'] ?? $user['email'];
        $data['score'] = @$param['score']  ?? $user['score'];
        $data['vip_time'] = getTime(2, $vip_time);
        $data['status'] = @$param['status']  ?? $user['status'];
        $res = Db::name('user')->where(['id' => $uid])->update($data);
        if ($res) success();
        error();
    }
    public function del()
    {
        $id = explode(',', $_GET['id']);
        $res = Db::name('user')->whereIn('id', $id)->delete();
        if ($res) success();
        error();
    }
    public function add()
    {
        $this->view('add');
    }
    public function doAdd()
    {
        $param = $_POST;
        $rule = [
            'username|用户名' => 'require|min:6|max:12|alphaNum',
            'password|密码' => 'require|min:6|max:12|alphaNum',
            'status|状态' => 'in:1,0,2',
            'score|积分' => 'int|egt:0',
            'email|邮箱' => 'require|email',
            'vip_time|会员时长' => 'int'
        ];
        VerfiyParam::init($param, $rule);
        $param['vip_time'] = $param['vip_time'];
        $param['role'] = 1;
        $res = Db::name('user')->insert($param);
        if ($res) success();
        error();
    }
}
